import React, { useEffect, useState, useRef, memo } from 'react';
import { useModel, history, useSearchParams } from '@umijs/max';
import {
  PlusOutlined,
  LoadingOutlined,
  CloseCircleOutlined,
} from '@ant-design/icons';
import {
  Form,
  Select,
  Space,
  Button,
  Checkbox,
  Divider,
  Input,
  Radio,
  Card,
  Image,
  Tooltip,
} from 'antd';
import styles from './index.less';
import { getUnique } from '@/utils/utils';
import Upload from '@/components/Upload';
import { useCallback } from 'react';
import { message } from 'antd';

export default (props) => {
  const { value, onChange } = props;
  const [spuList, setSpuList] = useState(value || []);
  const { SetSpu, Disabled, FormRef } = useModel('Goods');
  const triggerChange = useRef(false);
  const spuListData = useRef(value || []);

  useEffect(() => {
    SetSpu(spuList || []);
  }, [spuList]);

  const resetSpu = () => {
    handleChange([...spuListData.current]);
  };

  const handleChange = (newList) => {
    spuListData.current = newList;
    SetSpu(newList || []);
    setSpuList(newList);
    onChange(newList);
  };

  const handleRemoveSpu = (id) => {
    const newList = spuListData.current.filter((it) => it.id !== id);
    handleChange(newList);
  };

  const addSpu = () => {
    const newSpuId = getUnique();
    const newList = [
      ...spuListData.current,
      {
        id: newSpuId,
        values: [
          {
            id: `sku_${getUnique()}`,
          },
        ],
      },
    ];

    const data = [
      {
        id: `sku_${getUnique()}`,
      },
    ];
    FormRef.current.setFieldValue(`spu_value_${newSpuId}`, data);
    handleChange(newList);
  };

  const checkSpuExist = (item, value) => {
    const exist = spuListData.current.find(i => i.name === value && i.id !== item.id)
    if (exist) {
      for (let n = 1; n > 0; n++) {
        let name = `${value}(${n})`
        if (!spuListData.current.find(i => i.name === name && i.id !== item.id)) {
          // message.warning('同规格下规格值不可重复')
          return name
        }
      }
    } else {
      return value
    }
  }

  return (
    <Card>
      {spuList.length
        ? spuList.map((spu, index) => (
            <RenderSpuListItem
              spu={spuListData.current[index]}
              index={index}
              key={spu.id}
              spuList={spuList}
              handleRemoveSpu={handleRemoveSpu}
              resetSpu={resetSpu}
              checkSpuExist={checkSpuExist}
            />
          ))
        : null}
      {!Disabled && spuList.length < 3 ? (
        <div className={styles.spu_title_line}>
          <Button icon={<PlusOutlined />} onClick={addSpu}>
            添加规格项目
          </Button>
        </div>
      ) : null}
    </Card>
  );
};

const RenderSpuListItem = memo(
  ({ spu, index, checkSpuExist, handleRemoveSpu, resetSpu }) => {
    // const hasPic = spu?.values
    //   ? Boolean(spu?.values.filter((i) => i.value_attribute).length)
    //   : false;
    const spuFormName = `spu_name_${spu.id}`
    const { FormRef, Disabled } = useModel('Goods');
    const [showPicLine, setShowPicLine] = useState(false);

    useEffect(() => {
      if (spu?.values) {
        spu.values.forEach((i) => {
          if (i.value_attribute) {
            const formName = `spu_sku_pic_${i.id}`;
            FormRef.current.setFieldValue(formName, i.value_attribute);

            if (!showPicLine) {
              setShowPicLine(true);
            }
          }
        });
      }
      FormRef.current;
    }, [spu]);

    const handleShowImg = (flag) => {
      setShowPicLine(flag);
      spu.hasPic = flag;
      resetSpu();
    };

    const handleSpuNameChange = (e) => {
      const value = e.target.value;
      const name = checkSpuExist(spu, value)
      FormRef.current.setFieldValue(spuFormName, name);

      spu.name = name;
      resetSpu();
    };

    return (
      <div key={spu.id}>
        <div className={styles.spu_title_line}>
          <Form.Item
            name={spuFormName}
            label="规格名"
            rules={[{ required: true, message: '请输入商品规格！' }]}
            style={{ width: '180px' }}
          >
            <Input
              disabled={Disabled}
              suffix={
                Disabled ? null : (
                  <Tooltip title="删除该规格名">
                    <CloseCircleOutlined
                      onClick={() => handleRemoveSpu(spu.id)}
                      className={styles.close_icon}
                    />
                  </Tooltip>
                )
              }
              onBlur={handleSpuNameChange}
            />
          </Form.Item>
          {index === 0 ? (
            <Checkbox
              onChange={(e) => handleShowImg(e.target.checked)}
              checked={showPicLine}
              disabled={Disabled}
            >
              添加规格图片
            </Checkbox>
          ) : null}
        </div>
        <div className={styles.spu_content}>
          <Form.Item
            name={`spu_value_${spu.id}`}
            label="规格值"
            rules={[{ required: true, message: '请输入规格值！' }]}
            help={
              index
                ? ''
                : '仅支持为第一组规格设置规格图片（图片对应规格值，最多10个），用户在选择不同规格会看到对应规格图片，建议尺寸：800 x 800像素正方形图片'
            }
          >
            <SpuItemWrapper
              spu={spu}
              showPic={showPicLine}
              resetSpu={resetSpu}
            />
          </Form.Item>
        </div>
      </div>
    );
  },
  (pp, np) => pp.spu.id === np.spu.id && pp.index === np.index,
);

const SpuItemWrapper = ({ spu, showPic, resetSpu, ...props }) => {
  const { onChange } = props;
  const [skuList, setSkuList] = useState(spu.values || []);
  const skuListData = useRef(spu.values || []);
  const { Disabled } = useModel('Goods');

  // useEffect(() => {
  //   skuListData.current = skuList;
  //   onChange(skuList);
  //   console.log('skuList change', skuList)
  //   resetSpu();
  // }, [skuList]);

  const handleChange = (newList) => {
    spu.values = newList;
    skuListData.current = newList;
    setSkuList(newList);
    onChange(newList);
    resetSpu();
  };

  const checkExist = (item, value) => {
    const exist = skuListData.current.find(i => (i.value === value || i.sku_value === value) && i.id !== item.id)
    if (exist) {
      for (let n = 1; n > 0; n++) {
        let name = `${value}(${n})`
        if (!skuListData.current.find(i => (i.value === name || i.sku_value === name) && i.id !== item.id)) {
          // message.warning('同规格下规格值不可重复')
          return name
        }
      }
    } else {
      return value
    }
  }

  const addSku = () => {
    const newSku = { id: `sku_${getUnique()}` };
    const newList = [...skuList, newSku];
    handleChange(newList);
  };

  const handleRemoveSku = useCallback((id) => {
    const newList = [...skuListData.current.filter((it) => it.id !== id)];
    handleChange(newList);
  }, []);

  return (
    <Space wrap size="large">
      {skuList.map((sku, skuIndex) => (
        <Spu
          skuItem={sku}
          skuIndex={skuIndex}
          showPic={showPic}
          handleRemoveSku={handleRemoveSku}
          key={sku.id || getUnique()}
          resetSpu={resetSpu}
          checkExist={checkExist}
        />
      ))}
      {!Disabled && skuList && skuList.length < 10 ? (
        <Button type="link" icon={<PlusOutlined />} onClick={addSku}>
          添加规格值
        </Button>
      ) : null}
    </Space>
  );
};

const Spu = React.memo(
  ({ skuItem, showPic, resetSpu, handleRemoveSku, checkExist }) => {
    const [sku, setSku] = useState(skuItem);
    const formName = `spu_sku_name_${sku.id}`
    const { Disabled, FormRef } = useModel('Goods');

    const handleChange = (newItem) => {
      setSku(newItem);
      resetSpu();
    };

    const handleChagneSkuName = (value) => {
      const name = checkExist(skuItem, value)
      skuItem.sku_value = name;
      FormRef.current.setFieldValue(formName, name);
      
      handleChange({ ...skuItem }, );
    };

    const setSkuPic = (value, id) => {
      skuItem.value_attribute = value;
      handleChange({ ...skuItem });
    };

    const normFile = (e) => {
      if (e && e.length) {
        const { value, key } = e[0];

        setSkuPic(value, key);
        if (value) {
          return value;
        } else {
          return '';
        }
      } else {
        return '';
      }
    };

    return (
      <div className={styles.spu_item} key={sku.id}>
        <Form.Item
          name={formName}
          rules={[{ required: true, message: '请输入规格值名称！' }]}
        >
          <Input
            onBlur={(e) => handleChagneSkuName(e.target.value)}
            defaultValue={sku.sku_value}
            disabled={Disabled}
            style={{ width: '140px', marginBottom: showPic ? '10px' : '0' }}
            suffix={
              Disabled ? null : (
                <Tooltip title="删除该规格值">
                  <CloseCircleOutlined
                    onClick={() => handleRemoveSku(sku.id)}
                    className={styles.close_icon}
                  />
                </Tooltip>
              )
            }
          />
        </Form.Item>
        {showPic ? (
          <Form.Item
            name={`spu_sku_pic_${sku.id}`}
            label=""
            rules={[{ required: showPic, message: '请上传规格图片！' }]}
            valuePropName="value_attribute"
            getValueFromEvent={normFile}
            style={
              showPic
                ? null
                : { height: 0, margin: 0, padding: '0', overflow: 'hidden' }
            }
          >
            <Upload
              formProps={{
                name: 'file',
                listType: 'picture-card',
              }}
              key={`spu_sku_pic_${sku.id}`}
              maxCount={1}
              value={sku.value_attribute}
              disabled={Disabled}
            ></Upload>
          </Form.Item>
        ) : null}
      </div>
    );
  },
  (prevProps, nextProps) => {
    return (
      prevProps.skuItem.id === nextProps.skuItem.id &&
      prevProps.showPic === nextProps.showPic
    );
  },
);
